package com.loop.unclelend.ui.presenter

import com.loop.network.OkHttp
import com.loop.network.callback.StringCallback
import com.loop.network.model.Progress
import com.loop.network.model.Response
import com.loop.network.request.base.Request
import com.loop.unclelend.network.ApiService
import com.loop.unclelend.pro.ProPresenter
import com.loop.unclelend.ui.view.IView_Upload
import com.loop.unclelend.utils.log.UncleLog
import org.json.JSONObject
import java.io.File

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/12 18:45
 * @Annotation：上传图片
 */
class Pre_Upload(private val iView: IView_Upload): ProPresenter(iView) {

    /**
     * 上传图片
     */
    fun requestUploadImageAction(imgPath: String){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.UNCLE_API_UPLOAD_FILE_URL)
        OkHttp.post<String>(httpUrl) // 请求方式和请求url
            .tag(this) // 请求的 tag, 主要用于取消对应的请求
            .params("image", File(imgPath))   //这种方式为一个key，对应一个文件
            .isMultipart(true)
            .execute(object : StringCallback(){
                override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                    super.onStart(request)
                    UncleLog.e("upload start")
                }
                override fun onSuccess(response: Response<String>?) {
                    UncleLog.e("upload success ："+response!!.body())
                    if (response.code() == 200){
                        iView.hideUncleLoading()
                        val data = JSONObject(response.body())
                        when(data.optInt("code")){
                            0 -> {//成功
                                val imgUrl = data.optJSONObject("obj")!!.optString("url")
                                iView.showUncleUploadImageSuccess(imgPath,imgUrl)
                            }
                            else -> {
                                val msg = data.optString("msg")
                                iView.showUncleToast(msg)
                            }
                        }
                    } else {
                        iView.showUncleToast(response.message())
                    }
                }
                override fun onError(response: Response<String>?) {
                    UncleLog.e("upload error： "+response!!.body())
                    iView.showUncleToast(response.message())
                }
                override fun uploadProgress(progress: Progress) {
                    UncleLog.e("uploadProgress: $progress")
                    UncleLog.e("uploadProgress，total: ${progress.totalSize}")
                    UncleLog.e("uploadProgress，progress: ${progress.currentSize}")
                }
                override fun onFinish() {
                    iView.hideUncleLoading()
                }
            })
    }
}